package com.linkwechat.web.controller.system;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.linkwechat.common.config.TetantConfig;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.core.domain.entity.SysMenu;
import com.linkwechat.common.core.domain.entity.SysUser;
import com.linkwechat.common.core.domain.model.LoginBody;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.enums.TetantInfoTransferMode;
import com.linkwechat.common.enums.TetantType;
import com.linkwechat.common.utils.ServletUtils;
import com.linkwechat.common.tenant.TenantContextHolder;
import com.linkwechat.framework.web.service.SysLoginService;
import com.linkwechat.framework.web.service.SysPermissionService;
import com.linkwechat.framework.web.service.TokenService;

import com.linkwechat.system.domain.SysTenant;
import com.linkwechat.system.domain.SysTenantVo;
import com.linkwechat.system.service.ISysMenuService;
import com.linkwechat.system.service.ISysTenantService;
import com.linkwechat.system.service.ISysUserService;
import com.linkwechat.wecom.client.WeAccessTokenClient;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.client.WeAppClient;
import com.linkwechat.wecom.client.WeUserClient;
import com.linkwechat.wecom.domain.dto.WeLoginUserInfoDto;
import com.linkwechat.wecom.domain.dto.WeUserInfoDto;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;
import java.util.Set;


/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private IWeCorpAccountService iWxCorpAccountService;


    @Autowired
    private WeAccessTokenClient weAccessTokenClient;
    @Autowired
    private WeUserClient weUserClient;
    @Autowired
    private WeAppClient weAppClient;

    @Resource
    private TetantConfig tetantConfig;

    @Autowired
    private ISysTenantService tenantService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;



    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();

        // 生成令牌
        String token = null;

        // 获取租户信息
        if(tetantConfig.getType().equals(TetantType.NONE.getType())){
            token=loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
        }else if(tetantConfig.getType().equals(TetantType.COLUMN.getType())){

            if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_DOMAIN.getMode())){
                String tenantCode=TenantContextHolder.getTenantCode();
                if(tenantCode!=null){
                    token=loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                            loginBody.getUuid());
                }else{
                    ajax.setMsg("找不到对应租户信息，无法认证");
                }

            }else if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_QUERY_PARAM.getMode())){
                String tenantCode=TenantContextHolder.getTenantCode();
                if(StringUtils.isNotEmpty(tenantCode)){
                    token=loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                            loginBody.getUuid());
                }else{
                    ajax.setMsg("参数模式下无租户参数，无法认证");
                }
            }else if(tetantConfig.getTetantInfoTransferMode().equals(TetantInfoTransferMode.TRANSFER_MIXED.getMode())){
                String tenantCode=TenantContextHolder.getTenantCode();
                if(tenantCode!=null){
                    token=loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                            loginBody.getUuid());
                }else{
                    List<SysUser> sysUsers =TenantContextHolder.getSysUsers();
                    if(ObjectUtils.isNotEmpty(sysUsers)){
                        if(sysUsers.size()==1){
                            TenantContextHolder.setTenantCode(sysUsers.get(0).getTenantCode());
                            token=loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                                    loginBody.getUuid());
                        }else{
                            ajax.setMsg("该用户存在多个租户，请选择一个租户登录");
                        }
                    }else{
                        ajax.setMsg("找不到对应租户信息，无法认证");
                    }
                }
            }

        }else if(tetantConfig.getType().equals(TetantType.SCHEMA.getType())){

        }else if(tetantConfig.getType().equals(TetantType.DATABASE.getType())){

        }

        ajax.put(Constants.TOKEN, token);
        if(token==null){
            ajax.setCode(-1);
        }
        return ajax;
    }



    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);


        //校验用户是否拥有可用corpid
        WeCorpAccount wxCorpAccount
                = iWxCorpAccountService.findValidWeCorpAccount();
        if(null != wxCorpAccount){
            user.setValidCropId(true);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取企业扫码登录相关参数
     * @return
     */
    @GetMapping("/findWxQrLoginInfo")
    public AjaxResult findQrLoginParm(String tenant_code){

//        WeCorpAccount validWeCorpAccount
//                = iWxCorpAccountService.findValidWeCorpAccount();
        if(StringUtils.isEmpty(tenant_code)){
            tenant_code="0";
        }
        WeCorpAccount validWeCorpAccount=iWxCorpAccountService.findWeCorpByTenantCode(tenant_code);

        if(null != validWeCorpAccount){
            validWeCorpAccount.setContactSecret(null);
            validWeCorpAccount.setCorpSecret(null);
            validWeCorpAccount.setProviderSecret(null);
        }

        return AjaxResult.success(validWeCorpAccount);
    }



    /**
     * 扫码登录微信端回调
     * @param auth_code
     * @param appid
     * @return
     */
    @GetMapping("/wxQrLogin")
//    public AjaxResult wxQrLogin(String auth_code){
    public AjaxResult wxQrLogin(String auth_code,String appid){

        AjaxResult ajax = AjaxResult.success();
        WeCorpAccount weCorpAccount=iWxCorpAccountService.findWeCorpByCorpId(appid);
        TenantContextHolder.setTenantCode(weCorpAccount.getTenantCode());
// 服务商
//        WeLoginUserInfoDto loginInfo = weAppClient.getLoginInfo(auth_code);
//        if( null != loginInfo.getUser_info()){
//
//            String token = loginService.noPwdLogin(loginInfo.getUser_info().getUserid());
//            ajax.put(Constants.TOKEN, token);
//        }

        // 第三方应用
        WeUserInfoDto userInfo = weAppClient.getuserinfo(auth_code,weCorpAccount.getAgentId());
        if( null != userInfo){
            SysUser sysUser = sysUserService.selectUserByCorpUserId(userInfo.getUserId());
            if (null != sysUser){
                String token = loginService.noPwdLogin(sysUser.getUserName());
                ajax.put(Constants.TOKEN, token);
            }else {
                return AjaxResult.error("请绑定后再登录");
            }
        }


        return ajax;
    }

    @GetMapping("/getAllTenantInfo")
    public AjaxResult getAllTenantInfo(){
        AjaxResult ajax = AjaxResult.success();
        List<SysTenantVo> sysTenants=tenantService.getAllTenantInfo();
        ajax.setData(sysTenants);
        return ajax;
    }


    /**
     * 租户登录
     * @param corpId
     * @param corpSecret
     * @return
     */
    @GetMapping("/tenantLogin")
    public AjaxResult tenantLogin(String corpId,String corpSecret){
        AjaxResult ajax = AjaxResult.success();



        return ajax;
    }

}
